# ui/project_tree.py
import json
import os
import pandas as pd
from typing import Optional
from PySide6.QtWidgets import (
    QDockWidget, QTreeWidget, QTreeWidgetItem, QMenu, QInputDialog,
    QMessageBox, QLineEdit, QHeaderView
)
from PySide6.QtCore import Qt, Signal
from PySide6.QtGui import QIcon, QBrush, QColor, QAction
from ui.base_widget import BaseWidgetMixin
from utils.data_manager import DataManager
import logging

# 配置日志记录
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')


class ProjectTreeDock(QDockWidget, BaseWidgetMixin):
    """项目树停靠窗口"""

    visualization_requested = Signal(str)  # 请求可视化信号，参数为井名
    open_table_requested = Signal(str)  # 请求打开表格信号，参数为井名
    well_renamed = Signal(str, str)  # 井重命名信号，参数为旧井名和新井名
    well_deleted = Signal(str)  # 井删除信号，参数为井名

    dock_area = Qt.LeftDockWidgetArea  # 停靠位置

    def __init__(self, parent=None):
        # 调用QDockWidget的构造函数
        super().__init__("项目结构", parent)#解释: 设置停靠窗口的标题

        # 调用Mixin类的方法
        self.setup_styles()

        # 设置允许浮动和停靠
        self.setAllowedAreas(
            Qt.LeftDockWidgetArea |
            Qt.RightDockWidgetArea
        )

        # 项目数据管理器
        self.data_manager = DataManager()

        # 创建项目树
        self._create_tree()

        # 设置widget
        self.setWidget(self.tree)

        # 设置连接
        self.setup_connections()

        # 初始化数据
        self._refresh_tree()

    def _create_tree(self):
        """创建项目树"""
        self.tree = QTreeWidget()
        self.tree.setHeaderLabel("项目结构")
        self.tree.setContextMenuPolicy(Qt.CustomContextMenu)
        self.tree.setSelectionMode(QTreeWidget.SingleSelection)
        self.tree.setAnimated(True)  # 启用展开/折叠动画
        self.tree.setSortingEnabled(True)  # 启用排序
        self.tree.sortByColumn(0, Qt.AscendingOrder)

        # 设置列宽
        self.tree.header().setSectionResizeMode(0, QHeaderView.Stretch)

    def setup_connections(self):
        """连接信号和槽"""
        # 双击项目请求可视化
        self.tree.itemDoubleClicked.connect(self._on_item_double_clicked)
        self.tree.customContextMenuRequested.connect(self._show_context_menu)

    def _refresh_tree(self):
        """刷新项目树"""
        try:
            self.tree.clear()

            # 创建根节点
            root = QTreeWidgetItem(self.tree)
            root.setText(0, "井数据")
            root.setData(0, Qt.UserRole, {"type": "root"})

            # 设置根节点图标
            root.setIcon(0, QIcon(":/icons/folder-open.svg"))

            # 从数据模型获取井列表
            well_list = self.data_manager.get_well_list()

            # 添加井节点
            for well_name in well_list:
                well_data = self.data_manager.get_well_data(well_name)
                if well_data is None:
                    continue

                well_item = QTreeWidgetItem(root)
                well_item.setText(0, well_name)
                well_item.setData(0, Qt.UserRole, {"type": "well", "name": well_name})
                well_item.setIcon(0, QIcon(":/icons/well.svg"))

                # 添加基本信息子节点
                info_item = QTreeWidgetItem(well_item)
                info_item.setText(0, f"基本信息 ({len(well_data)} 行数据)")
                info_item.setData(0, Qt.UserRole, {"type": "info", "well_name": well_name})
                info_item.setIcon(0, QIcon(":/icons/info.svg"))

                # 添加曲线子节点
                curves_item = QTreeWidgetItem(well_item)
                curves_item.setText(0, "曲线")
                curves_item.setData(0, Qt.UserRole, {"type": "curves", "well_name": well_name})
                curves_item.setIcon(0, QIcon(":/icons/curves.svg"))

                # 添加各个曲线
                curve_names = list(well_data.columns)
                for curve_name in curve_names:
                    curve_item = QTreeWidgetItem(curves_item)
                    curve_item.setText(0, curve_name)
                    curve_item.setData(0, Qt.UserRole, {"type": "curve", "well_name": well_name, "curve_name": curve_name})
                    curve_item.setIcon(0, QIcon(":/icons/curve.svg"))

            # 展开根节点
            self.tree.expandItem(root)
        except Exception as e:
            logging.error(f"刷新项目树时出错: {e}")

    def _on_item_double_clicked(self, item, column):
        """处理项目双击事件"""
        try:
            data = item.data(0, Qt.UserRole)

            if data and data["type"] == "well":
                well_name = data["name"]
                # 发出可视化请求信号
                self.visualization_requested.emit(well_name)

            elif data and data["type"] == "curve":
                well_name = data["well_name"]
                # 双击曲线也触发可视化，但可以考虑其他行为
                self.visualization_requested.emit(well_name)
        except Exception as e:
            logging.error(f"处理项目双击事件时出错: {e}")

    def _show_context_menu(self, position):
        """显示上下文菜单"""
        item = self.tree.itemAt(position)

        if item:
            data = item.data(0, Qt.UserRole)

            if data and data["type"] == "well":
                menu = QMenu()

                # 添加可视化动作
                visualize_action = QAction("可视化", self)
                visualize_action.setIcon(QIcon(":/icons/visualize.svg"))
                visualize_action.triggered.connect(lambda: self._on_visualize_action(data["name"]))
                menu.addAction(visualize_action)

                # 添加打开表格动作
                open_table_action = QAction("打开数据表格", self)
                open_table_action.setIcon(QIcon(":/icons/table.svg"))
                open_table_action.triggered.connect(lambda: self._on_open_table_action(data["name"]))
                menu.addAction(open_table_action)

                menu.addSeparator()

                # 添加重命名动作
                rename_action = QAction("重命名", self)
                rename_action.setIcon(QIcon(":/icons/rename.svg"))
                rename_action.triggered.connect(lambda: self._on_rename_action(data["name"]))
                menu.addAction(rename_action)

                # 添加删除动作
                delete_action = QAction("删除", self)
                delete_action.setIcon(QIcon(":/icons/delete.svg"))
                delete_action.triggered.connect(lambda: self._on_delete_action(data["name"]))
                menu.addAction(delete_action)

                menu.exec_(self.tree.viewport().mapToGlobal(position))

            elif data and data["type"] == "curve":
                menu = QMenu()

                # 添加查看数据动作
                view_data_action = QAction("查看曲线数据", self)
                view_data_action.triggered.connect(
                    lambda: self._on_view_curve_data(data["well_name"], data["curve_name"]))
                menu.addAction(view_data_action)

                menu.exec_(self.tree.viewport().mapToGlobal(position))

    def _on_visualize_action(self, well_name):
        """处理可视化动作"""
        try:
            self.visualization_requested.emit(well_name)
        except Exception as e:
            logging.error(f"处理可视化动作时出错: {e}")

    def _on_open_table_action(self, well_name):
        """处理打开表格动作"""
        try:
            self.open_table_requested.emit(well_name)
        except Exception as e:
            logging.error(f"处理打开表格动作时出错: {e}")

    def _on_rename_action(self, well_name):
        """处理重命名动作"""
        try:
            current_item = self._find_well_item(well_name)
            if not current_item:
                return

            new_name, ok = QInputDialog.getText(
                self,
                "重命名井",
                "请输入新的井名:",
                text=well_name
            )

            if ok and new_name and new_name != well_name:
                # 检查新名称是否已存在
                if new_name in self.data_manager.get_well_list():
                    QMessageBox.warning(self, "警告", f"井名 '{new_name}' 已存在!")
                    return

                # 重命名井
                if self.data_manager.rename_well(well_name, new_name):
                    # 更新树
                    current_item.setText(0, new_name)
                    current_item.setData(0, Qt.UserRole, {"type": "well", "name": new_name})

                    # 更新子节点数据
                    for i in range(current_item.childCount()):
                        child = current_item.child(i)
                        child_data = child.data(0, Qt.UserRole)
                        if child_data and "well_name" in child_data:
                            child_data["well_name"] = new_name
                            child.setData(0, Qt.UserRole, child_data)

                    # 发出重命名信号
                    self.well_renamed.emit(well_name, new_name)
                else:
                    QMessageBox.critical(self, "错误", f"无法重命名井 '{well_name}'")
        except Exception as e:
            logging.error(f"处理重命名动作时出错: {e}")

    def _on_delete_action(self, well_name):
        """处理删除动作"""
        try:
            reply = QMessageBox.question(
                self,
                "确认删除",
                f"确定要删除井 '{well_name}' 吗?\n此操作不可撤销。",
                QMessageBox.Yes | QMessageBox.No,
                QMessageBox.No
            )

            if reply == QMessageBox.Yes:
                # 删除井
                if self.data_manager.delete_well(well_name):
                    # 刷新树
                    self._refresh_tree()

                    # 发出删除信号
                    self.well_deleted.emit(well_name)
                else:
                    QMessageBox.critical(self, "错误", f"无法删除井 '{well_name}'")
        except Exception as e:
            logging.error(f"处理删除动作时出错: {e}")

    def _on_view_curve_data(self, well_name, curve_name):
        """处理查看曲线数据动作"""
        try:
            well_data = self.data_manager.get_well_data(well_name)
            if well_data is None or curve_name not in well_data.columns:
                QMessageBox.warning(self, "警告", f"找不到曲线 '{curve_name}' 的数据")
                return

            # 这里可以打开一个对话框显示曲线数据
            # 简化实现，实际应该创建一个专门的对话框
            curve_data = well_data[[self.data_manager.get_depth_column(), curve_name]]

            # 可以考虑使用QTableView显示数据
            print(f"查看曲线数据: {well_name} - {curve_name}")
            print(curve_data.head())
        except Exception as e:
            logging.error(f"处理查看曲线数据动作时出错: {e}")

    def _find_well_item(self, well_name) -> Optional[QTreeWidgetItem]:
        """查找指定井名的树节点"""
        root = self.tree.topLevelItem(0)
        if not root:
            return None

        for i in range(root.childCount()):
            item = root.child(i)
            item_data = item.data(0, Qt.UserRole)
            if item_data and item_data["type"] == "well" and item_data["name"] == well_name:
                return item

        return None

    def add_well(self, well_name, well_data) -> bool:
        """添加新井"""
        try:
            if self.data_manager.add_well(well_name, well_data):
                self._refresh_tree()
                return True
            return False
        except Exception as e:
            logging.error(f"添加新井时出错: {e}")
            return False

    def update_well(self, well_name, well_data) -> bool:
        """更新井数据"""
        try:
            if self.data_manager.update_well(well_name, well_data):
                self._refresh_tree()
                return True
            return False
        except Exception as e:
            logging.error(f"更新井数据时出错: {e}")
            return False

    def delete_well(self, well_name) -> bool:
        """删除井"""
        try:
            if self.data_manager.delete_well(well_name):
                self._refresh_tree()
                return True
            return False
        except Exception as e:
            logging.error(f"删除井时出错: {e}")
            return False

    def refresh(self):
        """刷新项目树"""
        self._refresh_tree()